package com.peter.viewpager2;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private ViewPager2 fragment_vp2;
    DemoFragmentAdapter mAdapter;

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragmentvp2activity);

        fragment_vp2 = findViewById(R.id.vp2_fragment);
        mAdapter = new DemoFragmentAdapter(this);
        fragment_vp2.setAdapter(mAdapter);

        fragment_vp2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
//                Log.e(TAG, "onPageScrolled: " + position + " " + positionOffset + " " + positionOffsetPixels, null);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                Log.e(TAG, "onPageSelected: " + position, null);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                Log.e(TAG, "onPageScrollStateChanged: " + state, null);
            }
        });

        fragment_vp2.addItemDecoration(new RecyclerView.ItemDecoration() {

            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int space = 12;
                if (parent.getChildAdapterPosition(view) == 0) {

                    outRect.top = space;
                }
                outRect.bottom = space;
                view.setBackgroundColor(Color.parseColor("#DDDDDD"));
            }
        });

    }

    //设置方向 ViewPager2 独有
    public void setOrientationOnClick(View v) {
        if (fragment_vp2.getOrientation() == ViewPager2.ORIENTATION_HORIZONTAL) {
            fragment_vp2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        } else {
            fragment_vp2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        }
    }

    //添加一个fragment
    public void addFragmentOnClick(View v) {
        mAdapter.addFragment(new DemoFragment());
    }

    //删除一个fragment
    public void removeFragmentOnClick(View v) {
        mAdapter.removeFragment();
    }


}